package com.cfg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cfg.domain.*;
import com.cfg.service.CfgCategoryEntryService;
import com.cfg.service.CfgCategoryMappingService;
import com.cfg.service.CfgCategoryService;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.common.core.domain.entity.SysDept;
import com.common.core.domain.entity.SysUser;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cfg")
@Api(tags = "通用配置")
public class CfgCategoryController extends BaseController {
    @Autowired
    public CfgCategoryService cfgCategoryService;
    @Autowired
    public CfgCategoryEntryService cfgCategoryEntryService;
    @Autowired
    public CfgCategoryMappingService cfgCategoryMappingService;

    @Autowired
    private ISysDeptService deptService;

    @GetMapping("/getCategory")
    @ApiOperation(value = "获取通用配置")
    public AjaxResult getCategory(CfgCategory getCategory)
    {
        QueryWrapper<CfgCategory>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(getCategory.getBizName()),"bizname",getCategory.getBizName())
                .eq(StringUtils.isNotEmpty(getCategory.getCategoryName()),"categoryName",getCategory.getCategoryName());
        CfgCategory cfgCategory=cfgCategoryService.getOne(queryWrapper);
        if(cfgCategory==null){
            return error("分类不存在");
        }
        if(getCategory.getBizName().equals("成果归属单位")){
            SysUser user= SecurityUtils.getLoginUser().getUser();
            String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
            if(StringUtils.isNotNull(currentRoleKey)&&currentRoleKey.equals("biz_kyms")){
            String scope= user.getUnitAdminScope();
            if(StringUtils.isNull(scope)){
                return error("秘书管理单位不存在");
            }
               List<String> list = Arrays.asList(scope.split(","));
               List<SysDept>sysDepts=deptService.listByIds(list);
                if(StringUtils.isNull(sysDepts)){
                    return error("秘书管理单位数据不存在");
                }
                List<SimpleCfgCategoryMapping>bb=sysDepts.stream().map(this::Convert2SimpleCfgCategoryMapping)
                        .collect(Collectors.toList());
                return success(bb);
            }
        }

        //先找cfg_category_entry表 如果没有则找cfg_category_mapping表
        QueryWrapper<CfgCategoryEntry> cfgCategoryEntryQueryWrapper=new QueryWrapper<CfgCategoryEntry>();
        cfgCategoryEntryQueryWrapper.eq("categoryid",cfgCategory.getId());
        List<CfgCategoryEntry>cfgCategoryEntryList=cfgCategoryEntryService.list(cfgCategoryEntryQueryWrapper);
        if(cfgCategoryEntryList!=null&&cfgCategoryEntryList.size()>0){
            return success(cfgCategoryEntryList);
        }
        else  {
            QueryWrapper<CfgCategoryMapping> cfgCategoryMappingQueryWrapper = new QueryWrapper<CfgCategoryMapping>();
            cfgCategoryMappingQueryWrapper.eq("categoryid", cfgCategory.getId());
            CfgCategoryMapping cfgCategoryMapping = cfgCategoryMappingService.getOne(cfgCategoryMappingQueryWrapper);
            if(StringUtils.isNotEmpty(getCategory.getValueCascade())){
                cfgCategoryMapping.setValueCascade(getCategory.getValueCascade());
            }
            List<SimpleCfgCategoryMapping> simpleCfgCategoryMappingList = cfgCategoryMappingService.selectCfgMappingList(cfgCategoryMapping);
            if (simpleCfgCategoryMappingList == null) {
                return error("分类数据不存在");
            }
            if(cfgCategoryMapping.getUpcodeColumn()==null){
                return success(simpleCfgCategoryMappingList);
            }
            else {
                List<CfgTreeSelect> cfgTreeSelects = selectCfgTreeList(simpleCfgCategoryMappingList);
                return success(cfgTreeSelects);
            }
        }

    }

    @GetMapping("/getCategorys")
    @ApiOperation(value = "获取通用配置返回统一格式")
    public AjaxResult getCategorys(CfgCategory getCategory)
    {
        QueryWrapper<CfgCategory>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(getCategory.getBizName()),"bizname",getCategory.getBizName())
                .eq(StringUtils.isNotEmpty(getCategory.getCategoryName()),"categoryName",getCategory.getCategoryName());
        CfgCategory cfgCategory=cfgCategoryService.getOne(queryWrapper);
        if(cfgCategory==null){
            return error("分类不存在");
        }
        //先找cfg_category_entry表 如果没有则找cfg_category_mapping表
        QueryWrapper<CfgCategoryEntry> cfgCategoryEntryQueryWrapper=new QueryWrapper<CfgCategoryEntry>();
        cfgCategoryEntryQueryWrapper.eq("categoryid",cfgCategory.getId());
        List<CfgCategoryEntry>cfgCategoryEntryList=cfgCategoryEntryService.list(cfgCategoryEntryQueryWrapper);
        if(cfgCategoryEntryList!=null&&cfgCategoryEntryList.size()>0){
            return success(cfgCategoryEntryList);
        }
        else  {
            QueryWrapper<CfgCategoryMapping> cfgCategoryMappingQueryWrapper = new QueryWrapper<CfgCategoryMapping>();
            cfgCategoryMappingQueryWrapper.eq("categoryid", cfgCategory.getId());
            CfgCategoryMapping cfgCategoryMapping = cfgCategoryMappingService.getOne(cfgCategoryMappingQueryWrapper);
            if(StringUtils.isNotEmpty(getCategory.getValueCascade())){
                cfgCategoryMapping.setValueCascade(getCategory.getValueCascade());
            }
            List<SimpleCfgCategoryMapping> simpleCfgCategoryMappingList = cfgCategoryMappingService.selectCfgMappingList(cfgCategoryMapping);
            if (simpleCfgCategoryMappingList == null) {
                return error("分类数据不存在");
            }
            if(cfgCategoryMapping.getUpcodeColumn()==null){
          List<CfgCategoryEntry>bb=simpleCfgCategoryMappingList.stream().map(this::Convert2CfgCategoryEntry)
                        .collect(Collectors.toList());
                return success(bb);
            }
            else {
                List<CfgCategoryEntry> cfgTreeSelects = buildCategoryEntryTree(simpleCfgCategoryMappingList);
                return success(cfgTreeSelects);
            }
        }

    }

    public CfgCategoryEntry Convert2CfgCategoryEntry(SimpleCfgCategoryMapping simpleCfgCategoryMapping){

        CfgCategoryEntry cfgCategoryEntry=new CfgCategoryEntry();
        cfgCategoryEntry.setCode(simpleCfgCategoryMapping.getCodeColumn());
        cfgCategoryEntry.setName(simpleCfgCategoryMapping.getValueColumnLocal());
        return  cfgCategoryEntry;
    }

    public SimpleCfgCategoryMapping Convert2SimpleCfgCategoryMapping(SysDept sysDept){

        SimpleCfgCategoryMapping simpleCfgCategoryMapping=new SimpleCfgCategoryMapping();
        simpleCfgCategoryMapping.setCodeColumn(sysDept.getDeptRealId());
        simpleCfgCategoryMapping.setValueColumn(sysDept.getDeptName());
        simpleCfgCategoryMapping.setUpcodeColumn("upcodeColumn");
        return  simpleCfgCategoryMapping;
    }



    public List<CfgTreeSelect> selectCfgTreeList(List<SimpleCfgCategoryMapping> depts)
    {

        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */

    public List<CfgTreeSelect> buildDeptTreeSelect(List<SimpleCfgCategoryMapping> depts)
    {
        List<SimpleCfgCategoryMapping> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(CfgTreeSelect::new).collect(Collectors.toList());
    }
    public List<CfgCategoryEntry> buildCategoryEntryTree(List<SimpleCfgCategoryMapping> depts)
    {
        List<SimpleCfgCategoryMapping> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(CfgCategoryEntry::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */

    public List<SimpleCfgCategoryMapping> buildDeptTree(List<SimpleCfgCategoryMapping> depts)
    {
        List<SimpleCfgCategoryMapping> returnList = new ArrayList<SimpleCfgCategoryMapping>();
        List<String> tempList = depts.stream().map(SimpleCfgCategoryMapping::getCodeColumn).collect(Collectors.toList());
        for (SimpleCfgCategoryMapping dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getUpcodeColumn()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SimpleCfgCategoryMapping> list, SimpleCfgCategoryMapping t)
    {
        // 得到子节点列表
        List<SimpleCfgCategoryMapping> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SimpleCfgCategoryMapping tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SimpleCfgCategoryMapping> getChildList(List<SimpleCfgCategoryMapping> list, SimpleCfgCategoryMapping t)
    {
        List<SimpleCfgCategoryMapping> tlist = new ArrayList<SimpleCfgCategoryMapping>();
        Iterator<SimpleCfgCategoryMapping> it = list.iterator();
        while (it.hasNext())
        {
            SimpleCfgCategoryMapping n = (SimpleCfgCategoryMapping) it.next();
            if (StringUtils.isNotNull(n.getUpcodeColumn()) && n.getUpcodeColumn().equals(t.getCodeColumn()) )
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SimpleCfgCategoryMapping> list, SimpleCfgCategoryMapping t)
    {
        return getChildList(list, t).size() > 0;
    }



}
